package com.metaverse.backend.utils;


import com.anji.captcha.util.StringUtils;
import com.metaverse.backend.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * Created by IDEA
 * User: mashaohua
 * Date: 2016-10-19 10:21
 * Desc:
 */
@Component
@Slf4j
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    private static Environment env;

    private static boolean runDev;

    private static boolean runTest;

    private static boolean runProd;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextUtil.context = context;
        //初始化记录应用环境
        ApplicationContextUtil.env = context.getBean(Environment.class);
        List<String> envList = Arrays.asList(env.getActiveProfiles());
        log.info("当前激活配置：" + envList);
        if(envList.contains("dev")){
            runDev = true;
        }
        if(envList.contains("test")){
            runTest = true;
        }
        if(envList.contains("prod")){
            runProd = true;
        }

    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static boolean isRunDev() {
        return runDev;
    }

    public static boolean isRunTest() {
        return runTest;
    }

    public static boolean isRunProd() {
        return runProd;
    }

    /**
     * 最高级别管理员
     * @return
     */
    public static boolean isHighestAdmin(User user){
        String highestAdmin = env.getProperty("highestAdmin");
        if(StringUtils.isBlank(highestAdmin)){
            return false;
        }

        List<String> authedUsers = Arrays.asList(highestAdmin.split(","));
        if(user != null && authedUsers.contains(user.getOpenid())){
            return true;
        }

        return false;
    }


    /**
     * 获得当前web请求对象
     * @return
     */
    public static HttpServletRequest currentRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();
            return request;
        }
        return null;
    }



}
